<template>
  <section style="border: 0px solid red;margin-top: -10px">
    <el-row>
      <el-button size="mini" type="text" @click="loadMallGoodsDialog=true" style="margin-bottom: 10px;float:right;">导入产品</el-button>
    </el-row>
    <!--<el-button size="mini" type="text" @click="test">测试</el-button>-->
    <el-collapse v-model="activeNames">
      <el-collapse-item title="基本信息" name="1">
        <template slot="title">
          <span class="title">一、基本信息</span>
        </template>
        <el-row v-show="activeNames.findIndex(an=>an === '1') >=0">
          <new-mall-goods :goodsBase="goodsBase" v-on:newSuccess="newSuccessEvent"></new-mall-goods>
        </el-row>
      </el-collapse-item>
      <el-collapse-item title="商品规格" name="2">
        <template slot="title">
          <span class="title">二、商品规格</span>
        </template>
        <el-row  v-show="activeNames.findIndex(an=>an === '2') >=0">
          <el-row style="margin:8px 0;font-weight: bold">
            <el-col :span="2"><span>属性：</span></el-col>
            <el-col :span="20">
              <el-tag size="small" style="margin:0 2px;" :key="index" v-for="(t,index) in testTitle" :closable="testTitle.length > 0 && propsList.length<=0" :disable-transitions="false" @close="handleClose(index)">
                {{t}}
              </el-tag>
              <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="mini" @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm">
              </el-input>
              <el-button v-else v-show="propsList.length==0" class="button-new-tag" size="mini" @click="showInput"> + </el-button>
            </el-col>
          </el-row>
          <el-row >
            <el-table :data="propsList" >
              <el-table-column type="index" width="50"></el-table-column>
              <el-table-column v-for="(t,index) in testTitle" :key="index" :label="t" v-if="propsList.length>0 || testTitle.length>0">
                <template slot-scope="scope">
                  <el-input v-if="scope.row.edit" size="mini" v-model="propsList[scope.$index][t]"></el-input>
                  <div v-if="!scope.row.edit">
                    {{propsList[scope.$index][t]}}
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="price" label="价格"  width="100" >
                <template slot-scope="scope">
                  <el-input v-if="scope.row.edit" size="mini" v-model="scope.row.price"></el-input>
                  <div v-else>{{scope.row.price}}</div>
                </template>
              </el-table-column>
              <el-table-column label="折扣价">
                <template slot-scope="scope">
                  <el-input v-if="scope.row.edit" size="mini" v-model="scope.row.sale"></el-input>
                  <div v-else>{{scope.row.sale}}</div>
                </template>
              </el-table-column>
              <el-table-column prop="sn" label="产品编号" width="200" >
                <template slot-scope="scope">
                  <div class="sn-box">
                  <el-input v-if="scope.row.edit" size="mini" v-model="scope.row.sn"></el-input>
                  <el-button v-if="scope.row.edit" @click='creatNumber(scope.row)' size="mini" type="text">生成</el-button>
                  <div v-else size="mini" slot="reference">{{scope.row.sn}}</div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="业务类型" width="155" >
                <template slot-scope="scope">
                  <business-type :disabled="!scope.row.edit" :code="scope.row.businessTypeCode" v-on:selType="scope.row.businessTypeCode = $event"></business-type>
                </template>
              </el-table-column>
              <el-table-column label="属性" width="255" >
                <template slot-scope="scope">
                  <sel-prop :disabled="!scope.row.edit" :typeData="scope.row"/>
                  <sel-sale :disabled="!scope.row.edit" :sku="scope.row"></sel-sale>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="155">
                <template slot-scope="scope">
                  <i class="el-icon-check" style="color:green;font-size: 16px;width:20px;text-align: center;" @click="createSkuBtn(scope.row)" v-if="!scope.row.id" />
                  <i :class="scope.row.edit?'el-icon-check':'el-icon-edit'" style="color:blue;font-size: 16px;width:20px;text-align: center;" @click="editSkuBtn(scope.row)" v-if="scope.row.id"/>
                  <i class="el-icon-minus" @click="cancelSkuBtn(scope)" v-if="scope.row.edit" style="font-size: 16px;width:20px;text-align: center;"/>
                  <i class="el-icon-close" style="color:red;font-size: 16px;width:20px;text-align: center;border:0px solid red;" @click="delSkuBtn(scope)" v-if="scope.row.id && !scope.row.edit"/>
                </template>
              </el-table-column>
            </el-table>
            <div class="btnBox" style="margin-top:10px">
              <el-button size="mini" @click="addSkuBtn" type="primary" icon="el-icon-plus"/>
            </div>
          </el-row>
        </el-row>
      </el-collapse-item>
      <el-collapse-item title="商品详情" name="3">
        <template slot="title">
          <span class="title">三、详情描述</span>
        </template>
        <el-row v-show="activeNames.findIndex(an=>an === '3') >=0" >
          <goods-detail :goodsDetails="goodsDetails" v-if="goodsDetails"></goods-detail>
        </el-row>
      </el-collapse-item>
    </el-collapse>
    <el-dialog title="导入" :visible.sync="loadMallGoodsDialog" append-to-body>
      <load-by-product :companyId="department.companyId" v-on:confirm="selLoadEvent"></load-by-product>
    </el-dialog>
  </section>
</template>

<script>
  import selSale from '@/common/selSkuSale'
  import selProp from '@/common/selProp'
  import businessType from '@/common/businessType'
  import editor from '@/common/tinymce'
  import goodsDetail from './goodsDetail'
  import newMallGoods from './newMallGoods'
  import loadByProduct from './loadByProduct'
  import dateFormater from '@/common/date-formater'
  import {mapGetters, mapActions, mapMutations} from 'vuex'
  import errHandler from '@/assets/errHandler.js'
  import Vue from 'vue'//后续添加属性，需要vue联动
  export default {
    name: "editMallGoods",
    props:['mallGoods'],
    components:{loadByProduct,newMallGoods,editor,businessType,goodsDetail,selProp,selSale},
    data() {
      return {
        activeNames:['1','2'],
        loading:false,
        testTitle:[],
        propsList:[],
        inputVisible: false,
        inputValue: '',
        loadMallGoodsDialog:false,
        goodsSkus:null,
        goodsBase:null,
        goodsDetails:null,
        detailType:'mobile'
      }
    },
    watch:{
      mallGoods(nv,ov){
        if(nv){
          this.activeNames=['1','2']
          this.initGoodsBase(nv)
        }
      },
      goodsBase(nv,ov){
        console.log('watch---goodsBase-------',nv)
      },
      goodsSkus(nv,ov){
        if(nv) this.initGoodsSkus(nv)
      },
      propsList(nv,ov){
        if(nv.length <=0) this.testTitle=[]
      }
    },
    created(){
      console.log('当前商品-------------goodsskus',this.mallGoods)
      this.initGoodsBase(this.mallGoods)
    },
    computed: {
      ...mapGetters(['department']),
    },
    methods: {
      ...mapActions({
        fetch: 'fetch'
      }),
      newSuccessEvent(e){
        Vue.set(this.mallGoods,'id',e.id)
        Vue.set(this.mallGoods,'goodsType',e.goodsType)
        Vue.set(this.mallGoods,'title',e.title)
        Vue.set(this.mallGoods,'data',e.data)
        this.getGoodsDetails(e.id)
      },
      initGoodsBase(obj){
        this.goodsSkus=obj.goodsSkus
        this.goodsBase={ title:obj.title, goodsTypeId:obj.goodsTypeId,storeId:this.department.id,data:obj.data}
        if(obj.id){
          this.goodsBase.id = obj.id
          this.getGoodsDetails(obj.id)
        }else {
          this.$message({type:'info',message:'尚未创建商品！'})
        }
        if(obj.goodsPhoto) this.goodsBase.goodsPhoto = obj.goodsPhoto
        if(obj.goodsType){
          this.goodsBase.goodsTypeId=obj.goodsType.id
          this.goodsBase.goodsType=obj.goodsType
        }
        // console.log('新建之后-------',this.goodsBase)
      },
      getGoodsDetails(goodsId){
        // this.goodsDetails=[]
        this.fetch({name:"getGoodsDetailByGoodsId",data:{goodsId}})
          .then(res=>{
            // console.log('商品详情------------',res)
            let index1 =res.findIndex(r=>r.type === 1)
            if(index1 <0) res.push({detail:'',type:1,goodsId:this.mallGoods.id})
            let index2 = res.findIndex(r=>r.type === 2)
            if(index2 <0) res.push({detail:'',type:2,goodsId:this.mallGoods.id})
            this.goodsDetails=res
          })
          .catch(err=>{
            if(err.errCode === 'good_detail_not_create'){
              this.$message({type:'info',message:'该商品未创建详情'})
              this.goodsDetails=[{detail:'',type:1,goodsId:this.mallGoods.id},{detail:'',type:2,goodsId:this.mallGoods.id}]
              return
            }
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      initGoodsSkus(res){
        this.propsList=[]
        this.propsList =this.makePropsList(res)
        this.testTitle=[]
        this.testTitle = this.makeNew(this.propsList)
      },
      makePropsList(array){
        let prop=[]
        console.log('array没有么？？？',array)
        array.forEach(a=>{
          let propKV = a.props.split(';')
          if(propKV.length>0){
            let item={}
            propKV.forEach(pKV=>{
              let pkv=pKV.split(':')
              let k=pkv[0]
              let val=pkv[1]
              let tmp={}
              item[k]=val
              item.sn=a.sn
              item.price=a.price
              item.sale=a.sale
              item.edit=a.edit
              item.businessTypeCode=a.data.businessTypeCode
              item.props=a.data.props
              item.joinCoupon=a.joinCoupon
              item.joinSale=a.joinSale
              if(a.id){
                item.id=a.id
              }
            })
            // console.log('item----',item)
            prop.push(item)
          }
        })
        console.log('看下sku列表--------------',prop)
        return prop
      },
      checkProp(k){
        if(k == 'sn') return false
        if(k == 'price') return false
        if(k == 'id') return false
        if(k == 'edit') return false
        if(k == 'businessTypeCode') return false
        if(k == 'props') return false
        if(k == 'joinSale') return false
        if(k == 'joinCoupon') return false
        if(k == 'sale') return false
        return true
      },
      makeNew(prop){
        let testTitle=[]
        prop.forEach(p=>{
          for(let k in p){
            if(this.checkProp(k)){
              let index = testTitle.findIndex(t=>t === k)
              if(index<0) testTitle.push(k)
            }else {
              return
            }
            // if(k !== 'sn' && k !=='price'&& k !=='id'&& k !=='edit' && k!== 'businessTypeCode' && k !=='props' && k!=='joinSale'){
            //   let index = testTitle.findIndex(t=>t === k)
            //   if(index<0){
            //     testTitle.push(k)
            //   }
            // }

          }
        })
        return testTitle
      },
      getMallGoodsTypeList(){
        this.fetch({name:"getMallGoodsTypeList",data:{storeId:this.department.id}})
          .then(res=>{
            this.typeList = res
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      updateMallGoods(row){
        this.fetch({name:"updateMallGoods",data:{...row}})
          .then(res=>{
            this.getMallGoodsList()
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      selLoadEvent(array,product){
        console.log('aarrays sh---------',array)
        if(this.goodsBase.title === ''){
          this.goodsBase.title=product.name
        }
        let tmp1 =this.makePropsList(array)
        let title=this.makeNew(tmp1)
        if(this.mallGoods.goodsSkus.length > 0){//判断属性
          this.loading=true
          let tmp =this.judgeTitle(title)
          if(!tmp){
            this.$message({type:'error',message:'属性不符！'})
            return
          }
        }else {
          this.testTitle=title
        }
        //判断sn是否重复
        let ableSkus=[]
        let unableSkus=[]
        tmp1.forEach(ps=>{
          let tmp={...ps,edit:true,businessTypeCode:this.mallGoods.data.businessTypeCode,props:this.mallGoods.data.props}
          let index = this.propsList.findIndex(pl=>pl.sn === ps.sn)
          if(index<0){
            ableSkus.push(tmp)
          }else {
            unableSkus.push(tmp)
          }
        })
        if(ableSkus.length>0){//有可导入才加入
          this.propsList=this.propsList.concat(ableSkus)
          this.loadMallGoodsDialog=false
        }
        //有拦截做提示
        if(unableSkus.length>0)  this.$message({type:'info',message:'有重复sn被拦截，如有需要，请手动添加！'})
        this.loading=false
      },
      judgeTitle(title){
        let tL=title.length
        let ttL=this.testTitle.length
        if(tL !== ttL) return false
        for(let i=0;i<tL;i++){
          let index=this.testTitle.findIndex(tt=>tt === title[i])
          if(index <0) return false
        }
        return true
      },
      creatNumber(row){
        this.fetch({name:"createSn",data:{snType:16}})
          .then(res=>{
            row.sn = res.sn
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      showInput() {
        this.inputVisible = true
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus()
        })
      },
      handleClose(index) {
        this.testTitle.splice(index, 1)
      },
      handleInputConfirm() {
        let inputValue = this.inputValue.replace(/\s+/g,"");
        if (inputValue) {
          console.log('空格也进？？？',typeof inputValue)
          this.testTitle.push(inputValue)
        }
        this.inputVisible = false
        this.inputValue = ''
      },
      createSkuBtn(row){//确定规格按钮判断编辑还是新建
        if(!this.mallGoods.id){
          this.$message({type:'error',message:'请先创建商品！'})
          return
        }
        let props=this.makeProps(row)
        let data={sn:row.sn,price:row.price,props,data:{...row}}
        console.log('看数据-------',row,data)
        // return
        this.fetch({name:"createMallGoodsSku",data:{...data,goodsId:this.mallGoods.id}})
          .then(res=>{
            this.$message({type:'success',message:'新建成功！'})
            row.edit=false
            row.id=res.id
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      editSkuBtn(row){
        console.log('看下更新sku的数据--------',row)
        if(row.edit === undefined){
          Vue.set(row,'edit',true)//后续添加属性，需要vue联动
          return
        }
        if(row.edit){
          let props=this.makeProps(row)
          // let data=row.data?row.data:{}
          let params={id:row.id,props,sn:row.sn,price:row.price,sale:row.sale,joinCoupon:row.joinCoupon,joinSale:row.joinSale,
            data:row.data?row.data:{businessTypeCode:row.businessTypeCode,props:row.props}}
          console.log('看数据-------',row,params)
          // return
          this.updateMallGoodsSku(params,row)
        }else {
          row.edit=true
        }
      },
      updateMallGoodsSku(data,row){
        this.fetch({name:"updateMallGoodsSku",data})
          .then(res=>{
            this.$message({type:'success',message:'更新成功！'})
            row.edit=false
            console.log('更新成功后-----',this.mallGoods.goodsSkus,this.propsList)
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      makeProps(row,index){
        let props=''
        for(let k in row){
          if(this.checkProp(k)) props +=k+':'+row[k]+';'
          // if(k !== 'price' && k!=='sn' && k !=='id'&& k !=='edit' && k!== 'businessTypeCode' && k !=='props'){
          //   props +=k+':'+row[k]+';'
          // }
        }
        if(props.length>0)
          props = props.substring(0,props.length-1)

        return props
      },
      cancelSkuBtn(scope){
        if(scope.row.id === undefined){
          let index = this.propsList.findIndex(ps=>ps.sn === scope.row.sn)
          this.propsList.splice(index,1)
          return
        }
        if(scope.row.edit === undefined){
          Vue.set(scope.row,'edit',false)//后续添加属性，需要vue联动
        }else {
          scope.row.edit =false
        }
      },
      delSkuBtn(scope){
        this.$confirm('确认删除？')
          .then(()=> {
            this.fetch({name:"delMallGoodsSku",data:{id:scope.row.id}})
              .then(res=>{
                this.$message({type:'success',message:'删除成功！'})
                this.propsList.splice(scope.$index,1)
              })
              .catch(err=>{
                console.log(err)
                errHandler.handle(this,err)
              })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
            this.loading = false
          })
      },
      addSkuBtn(){//增加规格
        let tmp = {price:'0',sn:'',edit:true,businessTypeCode:this.mallGoods.data.businessTypeCode}
        this.propsList.push(tmp)
      },
    }
  }
</script>

<style scoped>
  .title{
    font-size: 17px;
    font-weight: bold;
  }
  .btnBox{
    display: flex;
    flex-direction:row-reverse;
  }
  .sn-box{
    display: flex;
    flex-direction: row;
  }
</style>
